#nullable enable

using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
using Application.Service.Users;
using Application.Core.Dto;
using Furion.DataEncryption;
using Application.Service.LogCache;

namespace Application.Web.Entry.Shared
{
    public partial class PasswordChangeModal
    {
        [Parameter]
        public string CurrentUserDisplayName { get; set; } = "";

        [Parameter]
        public string CurrentUserName { get; set; } = "";

        [Parameter]
        public int CurrentUserId { get; set; } = -1;

        [Parameter]
        public EventCallback OnPasswordChanged { get; set; }

        [Inject]
        private ILogger<PasswordChangeModal>? Logger { get; set; }

        [Inject]
        private UserService? _userService { get; set; }

        // 密码修改相关属性
        private string CurrentPassword { get; set; } = string.Empty;
        private string NewPassword { get; set; } = string.Empty;
        private string ConfirmPassword { get; set; } = string.Empty;
        private string PasswordErrorMessage { get; set; } = string.Empty;
        private string PasswordSuccessMessage { get; set; } = string.Empty;
        
        // 错误状态和按钮状态
        private bool IsCurrentPasswordError { get; set; } = false;
        private bool IsNewPasswordError { get; set; } = false;
        private bool IsConfirmPasswordError { get; set; } = false;
        private bool IsPasswordChangeSuccess { get; set; } = false;
        private bool IsPasswordChangeFailed { get; set; } = false;
        private bool IsChangingPassword { get; set; } = false;

        // 按钮状态辅助方法
        private string GetButtonClass()
        {
            if (IsPasswordChangeSuccess)
                return "btn-success";
            else if (IsPasswordChangeFailed)
                return "btn-danger";
            else if (IsChangingPassword)
                return "btn-secondary";
            else
                return "btn-primary";
        }

        private string GetButtonIcon()
        {
            if (IsPasswordChangeSuccess)
                return "fa-solid fa-check";
            else if (IsPasswordChangeFailed)
                return "fa-solid fa-times";
            else if (IsChangingPassword)
                return "fa-solid fa-spinner fa-spin";
            else
                return "fa-solid fa-key";
        }

        private string GetButtonText()
        {
            if (IsPasswordChangeSuccess)
                return "密码修改成功";
            else if (IsPasswordChangeFailed)
                return "密码修改失败";
            else if (IsChangingPassword)
                return "修改中...";
            else
                return "修改密码";
        }

        // 输入框样式类方法
        private string GetCurrentPasswordClass()
        {
            return IsCurrentPasswordError ? "form-control is-invalid" : "form-control";
        }

        private string GetNewPasswordClass()
        {
            return IsNewPasswordError ? "form-control is-invalid" : "form-control";
        }

        private string GetConfirmPasswordClass()
        {
            return IsConfirmPasswordError ? "form-control is-invalid" : "form-control";
        }

        // 焦点离开验证方法
        private async Task ValidateCurrentPassword()
        {
            if (!string.IsNullOrWhiteSpace(CurrentPassword))
            {
                try
                {
                    if (_userService != null && CurrentUserId > 0)
                    {
                        var user = await _userService.GetAsync(CurrentUserId);
                        if (user != null)
                        {
                            IsCurrentPasswordError = !MD5Encryption.Compare(MD5Encryption.Encrypt($"{Furion.App.GetConfig<string>("SecretKey")}{CurrentPassword}"), user.PasswordHash, true, false);
						}
                        else
                        {
                            IsCurrentPasswordError = true;
                        }
                    }
                    else
                    {
                        IsCurrentPasswordError = true;
                    }
                }
                catch (Exception ex)
                {
                    LogWrapper.Error("验证当前密码失败", exception:ex);
                    IsCurrentPasswordError = true;
                }
            }
            else
            {
                IsCurrentPasswordError = false;
            }
            
            StateHasChanged();
        }

        private void ValidateNewPassword()
        {
            if (!string.IsNullOrWhiteSpace(NewPassword))
            {
                IsNewPasswordError = NewPassword.Length < 6;
            }
            else
            {
                IsNewPasswordError = false;
            }
            
            // 如果确认密码已输入，需要重新验证确认密码
            if (!string.IsNullOrWhiteSpace(ConfirmPassword))
            {
                IsConfirmPasswordError = NewPassword != ConfirmPassword;
            }
            
            StateHasChanged();
        }

        private void ValidateConfirmPassword()
        {
            if (!string.IsNullOrWhiteSpace(ConfirmPassword))
            {
                IsConfirmPasswordError = NewPassword != ConfirmPassword;
            }
            else
            {
                IsConfirmPasswordError = false;
            }
            
            StateHasChanged();
        }

        // 实时验证确认密码 - 每次输入时比较对应位数字符
        private void ValidateConfirmPasswordRealTime()
        {
            if (!string.IsNullOrWhiteSpace(ConfirmPassword))
            {
                // 比较对应位数的字符
                if (ConfirmPassword.Length <= NewPassword.Length)
                {
                    // 比较已输入的部分
                    IsConfirmPasswordError = ConfirmPassword != NewPassword.Substring(0, ConfirmPassword.Length);
                }
                else
                {
                    // 如果确认密码长度超过新密码，直接标记错误
                    IsConfirmPasswordError = true;
                }
            }
            else
            {
                IsConfirmPasswordError = false;
            }
            
            StateHasChanged();
        }

        // 确认密码输入事件处理
        private void OnConfirmPasswordInput(ChangeEventArgs e)
        {
            ConfirmPassword = e.Value?.ToString() ?? "";
            // 这里不调用验证，让@onkeyup事件处理验证
        }

        // 清除输入框内容方法
        private void ClearCurrentPassword()
        {
            CurrentPassword = string.Empty;
            IsCurrentPasswordError = false;
            StateHasChanged();
        }

        private void ClearNewPassword()
        {
            NewPassword = string.Empty;
            IsNewPasswordError = false;
            IsConfirmPasswordError = false;
            StateHasChanged();
        }

        private void ClearConfirmPassword()
        {
            ConfirmPassword = string.Empty;
            IsConfirmPasswordError = false;
            StateHasChanged();
        }

        // 修改密码方法
        private async Task ChangePasswordAsync()
        {
            if (IsChangingPassword) return;

            // 重置状态
            IsPasswordChangeSuccess = false;
            IsPasswordChangeFailed = false;
            PasswordErrorMessage = string.Empty;
            PasswordSuccessMessage = string.Empty;

            // 验证输入
            if (string.IsNullOrWhiteSpace(CurrentPassword))
            {
                IsCurrentPasswordError = true;
                PasswordErrorMessage = "请输入当前密码";
                StateHasChanged();
                return;
            }

            if (string.IsNullOrWhiteSpace(NewPassword) || NewPassword.Length < 6)
            {
                IsNewPasswordError = true;
                PasswordErrorMessage = "新密码不能为空且长度不能少于6位";
                StateHasChanged();
                return;
            }

            if (string.IsNullOrWhiteSpace(ConfirmPassword) || NewPassword != ConfirmPassword)
            {
                IsConfirmPasswordError = true;
                PasswordErrorMessage = "确认密码不能为空且必须与新密码一致";
                StateHasChanged();
                return;
            }

            IsChangingPassword = true;
            StateHasChanged();

            try
            {
                if (_userService != null && CurrentUserId > 0)
                {
                    // 首先验证当前密码是否正确
                    var user = await _userService.GetAsync(CurrentUserId);
                    if (user == null)
                    {
                        IsPasswordChangeFailed = true;
                        PasswordErrorMessage = "用户不存在";
                        IsCurrentPasswordError = true;
                        return;
                    }

                    // 验证当前密码
                    bool isCurrentPasswordValid = MD5Encryption.Compare(MD5Encryption.Encrypt($"{Furion.App.GetConfig<string>("SecretKey")}{CurrentPassword}"), user.PasswordHash, true, false);
					
					if (!isCurrentPasswordValid)
                    {
                        IsPasswordChangeFailed = true;
                        PasswordErrorMessage = "当前密码错误，请重新输入";
                        IsCurrentPasswordError = true;
                        return;
                    }

                    // 使用UpdateAsync方法更新密码
                    var updateDto = new UserUpdateDto(
                        user.UserName,
                        MD5Encryption.Encrypt($"{Furion.App.GetConfig<string>("SecretKey")}{NewPassword}"), // 加密新密码
                        user.DisplayName,
                        user.IsDisabled
                    );

                    var result = await _userService.UpdateAsync(CurrentUserId, updateDto);

                    if (result.ok)
                    {
                        IsPasswordChangeSuccess = true;
                        PasswordSuccessMessage = "密码修改成功";

                        // 清空表单
                        CurrentPassword = string.Empty;
                        NewPassword = string.Empty;
                        ConfirmPassword = string.Empty;
                        IsCurrentPasswordError = false;
                        IsNewPasswordError = false;
                        IsConfirmPasswordError = false;

                        // 触发密码修改成功事件
                        await OnPasswordChanged.InvokeAsync();
                    }
                    else
                    {
                        IsPasswordChangeFailed = true;
                        PasswordErrorMessage = result.error ?? "密码修改失败";
                        LogWrapper.Error(PasswordErrorMessage);
                        IsCurrentPasswordError = true;
                    }
                }
                else
                {
                    IsPasswordChangeFailed = true;
                    PasswordErrorMessage = "用户服务不可用或用户ID无效";
                    LogWrapper.Error(PasswordErrorMessage);
                }
            }
            catch (Exception ex)
            {
                IsPasswordChangeFailed = true;
                PasswordErrorMessage = "修改密码时发生错误";
                LogWrapper.Error("修改密码时发生错误", exception:ex);
            }
            finally
            {
                IsChangingPassword = false;
                StateHasChanged();
            }
        }

        // 重置表单方法
        public void ResetForm()
        {
            CurrentPassword = string.Empty;
            NewPassword = string.Empty;
            ConfirmPassword = string.Empty;
            PasswordErrorMessage = string.Empty;
            PasswordSuccessMessage = string.Empty;
            IsCurrentPasswordError = false;
            IsNewPasswordError = false;
            IsConfirmPasswordError = false;
            IsPasswordChangeSuccess = false;
            IsPasswordChangeFailed = false;
            IsChangingPassword = false;
            
            StateHasChanged();
        }
    }
}